package service

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"sensi/app/api/dto"
	"sensi/app/model"
	"sensi/common/sys/database"
)

func (s *Service) PreviewDial(ctx *gin.Context) (interface{}, error) {
	req := &dto.PreviewDialReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}

	list, err := s.dialRepo.DialsByBroadcast(database.Instance(ctx), req.Broadcast)
	if err != nil {
		return nil, err
	}

	resp := struct {
		List []dto.PreviewDialResp `json:"list"`
	}{
		List: make([]dto.PreviewDialResp, 0),
	}
	for _, item := range list {
		resp.List = append(resp.List, dto.PreviewDialResp{
			UID:         item.UID,
			Name:        item.Name,
			Description: item.Description,
			Cover:       item.Cover,
			Type:        item.Type,
			Serial:      item.Serial,
			Broadcast:   item.Broadcast,
		})
	}

	return resp, nil
}

func (s *Service) ListDials(ctx *gin.Context) (interface{}, error) {
	list, err := s.dialRepo.Dials(database.Instance(ctx))
	if err != nil {
		return nil, err
	}

	return list, nil
}

func (s *Service) AddDial(ctx *gin.Context) (interface{}, error) {
	req := &dto.AddDialReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}

	m := &model.Dial{
		UID:         req.UID,
		Name:        req.Name,
		Description: req.Description,
		Cover:       req.Cover,
		Type:        req.Type,
		Serial:      req.Serial,
		Broadcast:   req.Broadcast,
	}

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) UpdateDial(ctx *gin.Context) (interface{}, error) {
	req := &dto.UpdateDialReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.dialRepo.GetByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty dial")
	}

	m.UID = req.UID
	m.Name = req.Name
	m.Description = req.Description
	m.Cover = req.Cover
	m.Type = req.Type
	m.Serial = req.Serial
	m.Broadcast = req.Broadcast

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) DeleteDial(ctx *gin.Context) (interface{}, error) {
	req := &dto.DeleteReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.dialRepo.GetByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty dial")
	}

	if err := database.Instance(ctx).Delete(m).Error; err != nil {
		return nil, err
	}

	return nil, nil
}
